<template>
  <div class="image-container">
    <el-card class="box-card">
      <div slot="header">
        <my-breadcrumb>素材管理</my-breadcrumb>
      </div>
      <div style="padding-bottom: 20px">
        <el-radio-group
          v-model="isCollected"
          size="mini"
          @change="hSwitchCollect"
        >
          <el-radio-button label="全部"></el-radio-button>
          <el-radio-button label="收藏"></el-radio-button>
        </el-radio-group>
        <el-button
          @click="dialogVisible = true"
          type="success"
          size="mini"
          style="float: right"
          >上传图片素材
        </el-button>
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="30%"
          append-to-body
        >
          <el-upload
            class="avatar-uploader"
            action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-image v-if="imageUrl" :src="imageUrl" @load="hImageLoad" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-dialog>
      </div>
      <!-- 素材列表 -->
      <el-row :gutter="10">
        <el-col
          :span="4"
          v-for="image in images"
          :key="image.id"
          class="img_item"
        >
          <el-image
            style="height: 180px; width: 180px"
            :src="image.url"
            fit="cover"
          ></el-image>
          <div class="option" v-show="isCollected === '全部'">
            <span
              class="el-icon-star-off"
              :class="{ red: image.is_collected }" @click="hSwitchCollectImage(image)"
            ></span>
            <span class="el-icon-delete" @click="hDelete(image)"></span>
          </div>
        </el-col>
      </el-row>
      <!-- /素材列表 -->
      <!-- 列表分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="per_page"
        @current-change="hPageChange"
        :total="total_count"
        :disabled="isLoading"
      >
      </el-pagination>
      <!-- /列表分页 -->
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ImageIndex',
  data () {
    return {
      isCollected: '全部',
      images: [],
      page: 1,
      total_count: 0,
      isLoading: false,
      per_page: 12,
      dialogVisible: false,
      imageUrl: '',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      }
    };
  },
  methods: {
    buildParams () {
      const params = {
        page: this.page,
        per_page: this.per_page,
        // 这是一个布尔值，若为true,则获取的是收藏的素材，若为false，获取的是全部素材
        collect: this.isCollected === '收藏'
      };
      return params;
    },
    async getImages () {
      const params = this.buildParams();
      this.isLoading = true
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/images',
          method: 'GET',
          params
        });
        this.images = res.data.data.results;
        this.total_count = res.data.data.total_count;
        this.isLoading = false
      } catch (err) {
        console.log(err);
        this.isLoading = false
      }
    },
    // 点击分页器回调
    hPageChange (curpage) {
      this.page = curpage;
      // 重新请求数据
      this.getImages();
    },
    // 切换全部、收藏的回调
    hSwitchCollect () {
      // 把页码重置为1
      this.page = 1;
      this.getImages();
    },
    hImageLoad () {
      setTimeout(() => {
        //   关闭弹出层
        this.dialogVisible = false
        // 重新加载数据
        this.getImages()
        // 清空数据项imageUrl
        this.imageUrl = ''
      }, 2000)
    },
    async doDelete (id) {
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/images/' + id,
          method: 'DELETE'
        })
        console.log(res);
        this.$message.success('删除成功~~~')
        // 重新请求数据
        this.getImages()
      } catch (err) {
        console.log(err);
        this.$message.error('删除失败~~~');
      }
    },
    hDelete (image) {
      this.$confirm('确认删除该图片吗？').then(() => {
        const id = image.id
        console.log(id);
        this.doDelete(id)
      }).catch(() => {
        console.log('取消了删除~~~')
      })
    },
    // 改变素材收藏状态
    async hSwitchCollectImage (image) {
      const id = image.id
      try {
        const res = this.$axios({
          url: '/mp/v1_0/user/images/' + id,
          method: 'PUT',
          data: {
            collect: !image.is_collected // 若现在是取消状态，则收藏，若现在是收藏，则取消
          }
        })
        console.log(res);
        // 此时不要重新加载数据，要动态改变这张图片的状态数据
        image.is_collected = !image.is_collected
      } catch (err) {
        console.log(err);
      }
    },
    // 上传成功的回调函数
    handleAvatarSuccess (res, file) {
      console.log(res);
      console.log(file);
      this.imageUrl = res.data.url

      // 2. 重新获取
      this.getImages()
    },
    // 上传图片格式及文件大小限制
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  },
  created () {
    this.getImages();
  }
};
</script>

<style lang="less" scoped>
.img_item {
  position: relative;
  box-sizing: border-box;
}
.option {
  position: absolute;
  left: 5px;
  width: 180px;
  bottom: 5px;
  height: 30px;
  line-height: 30px;
  background: rgba(0, 0, 0, 0.3);
  text-align: center;
  color: #fff;
  span {
    margin: 0 30px;
    cursor: pointer;
  }
}
.avatar-uploader {
  text-align: center;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.red {
  color: red;
}
</style>
